#!/bin/bash

declare -a ROOTFS_FILE_ARRAY
ROOTFS_FILE_ARRAY[0]="/usr/local/bin/pm_client"
ROOTFS_FILE_ARRAY[1]="/lib/systemd/system/pm_client.service"
ROOTFS_FILE_ARRAY[2]="/etc/udev/rules.d/70-persistent-net.rules"

function rootfs_install()
{
	echo "[$(basename $0)] ${FUNCNAME} $@"

	local REPO=${HOME}/nvidia/source_code/RK-JE313D2-S01-E2
	if [[ ! -d ${REPO} ]]; then
		git clone gitea@192.168.1.55:jiajia.wang/RK-JE313D2-S01-E2.git ${REPO}
	fi

	local TMPROOTFS=tmprootfs
	local FILE
	for FILE in ${ROOTFS_FILE_ARRAY[@]}; do
		local SRC="${REPO}/resources/rootfs/${FILE}"
		local DST="${TMPROOTFS}/${FILE}"
		if [[ -f ${SRC} ]]; then
			if [[ ! -d $(dirname ${DST}) ]]; then
				mkdir -p $(dirname ${DST})
			fi
			ln ${SRC} ${DST}
		fi
	done

	local TMPROOTFS_PATH=$(abs_path "${TMPROOTFS}")
	local TMPROOTFS_PATH_LEVEL=$(abs_path_level "${TMPROOTFS_PATH}")
	traverse ${TMPROOTFS_PATH} traverse_filter_none 0 traverse_exec_install ${TMPROOTFS_PATH_LEVEL} ${L4T_TOP}/rootfs
	rm -rf ${TMPROOTFS}

	echo "[$(basename $0)] Enable pm_client.service"
	sudo_cmd "ln -sf /lib/systemd/system/pm_client.service \
					 ${L4T_TOP}/rootfs/etc/systemd/system/multi-user.target.wants/pm_client.service"

}

function rootfs_uninstall()
{
	echo "[$(basename $0)] ${FUNCNAME} $@"

	local FILE
	for FILE in ${ROOTFS_FILE_ARRAY[@]}; do
		sudo_cmd "rm -f ${L4T_TOP}/rootfs/${FILE}"
	done

	sudo_cmd "rm -f  ${L4T_TOP}/rootfs/etc/systemd/system/multi-user.target.wants/pm_client.service"
}

#############################################################

if [[ $# -le 0 ]]; then
	exit 0
fi

case $1 in
	"install" )
		rootfs_install
		;;
	"uninstall" )
		rootfs_uninstall
		;;
esac
